package per.ethan.springboot.example.util;

import cn.hutool.core.date.DateTime;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;

import java.text.DecimalFormat;
import java.util.Date;

/**
 * @author Ethan
 * @date 2020/06/01 10:57
 */
@Slf4j
public class POIUtil {

    public static String getCellValue(Cell cell) {
        if (null == cell) {
            return "";
        }
        String type = "";
        CellType cellType = cell.getCellType();
        switch (cellType) {
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    type = formatter(cell);
                } else {
                    // 修正数据过大导致读取出来是科学计数形式
                    DecimalFormat format = new DecimalFormat("0");
                    type = String.valueOf(format.format(cell.getNumericCellValue()));
                }
                break;
            case STRING:
                type = cell.getStringCellValue();
                break;
            case BOOLEAN:
                type = String.valueOf(cell.getBooleanCellValue());
                break;
            case ERROR:
                log.error("数据类型错误: {}", cell.getColumnIndex());
                break;
            case BLANK:
            default:
                break;
        }
        return type;
    }

    private static String formatter(Cell cell) {
        String type = "";
        if (null != cell) {
            Date date = cell.getDateCellValue();
            type = new DateTime(date).toString("yyyy-MM-dd");
        }
        return type;
    }

}
